import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Upload, InputNumber, Switch } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, DragOutlined } from '@ant-design/icons';
import { request } from 'umi';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import moment from 'moment';

// 获取轮播图列表
const fetchBanners = async (params) => {
    return request('/api/v1/miniprogram/banner', {
        method: 'GET',
        params,
    });
};

// 创建轮播图
const createBanner = async (data) => {
    return request('/api/v1/miniprogram/banner', {
        method: 'POST',
        data,
    });
};

// 更新轮播图
const updateBanner = async (data) => {
    return request(`/api/v1/miniprogram/banner/${data.id}`, {
        method: 'PUT',
        data,
    });
};

// 删除轮播图
const deleteBanner = async (id) => {
    return request(`/api/v1/miniprogram/banner/${id}`, {
        method: 'DELETE',
    });
};

// 更新轮播图排序
const updateBannerSort = async (data) => {
    return request('/api/v1/miniprogram/banner/sort', {
        method: 'PUT',
        data,
    });
};

// 拖拽排序组件
const type = 'DraggableBodyRow';

const DraggableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
    const ref = React.useRef();
    const [{ isOver, dropClassName }, drop] = useDrop({
        accept: type,
        collect: monitor => {
            const { index: dragIndex } = monitor.getItem() || {};
            if (dragIndex === index) {
                return {};
            }
            return {
                isOver: monitor.isOver(),
                dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
            };
        },
        drop: item => {
            moveRow(item.index, index);
        },
    });
    const [, drag] = useDrag({
        type,
        item: { index },
        collect: monitor => ({
            isDragging: monitor.isDragging(),
        }),
    });
    drop(drag(ref));

    return (
        <tr
            ref={ref}
            className={`${className}${isOver ? dropClassName : ''}`}
            style={{ cursor: 'move', ...style }}
            {...restProps}
        />
    );
};

const BannerManagement = () => {
    const [banners, setBanners] = useState([]);
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [modalTitle, setModalTitle] = useState('添加轮播图');
    const [form] = Form.useForm();
    const [editingId, setEditingId] = useState(null);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    });

    // 获取轮播图列表
    const fetchBannerList = async () => {
        try {
            setLoading(true);
            const res = await fetchBanners({
                page: pagination.current,
                pageSize: pagination.pageSize,
            });
            if (res.success) {
                setBanners(res.data.list || []);
            } else {
                message.error(res.message || '获取轮播图列表失败');
            }
        } catch (error) {
            console.error('获取轮播图列表出错:', error);
            message.error('获取轮播图列表失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchBannerList();
    }, [pagination.current, pagination.pageSize]);

    // 处理拖拽排序
    const moveRow = async (dragIndex, hoverIndex) => {
        const dragRow = banners[dragIndex];
        const newData = update(banners, {
            $splice: [
                [dragIndex, 1],
                [hoverIndex, 0, dragRow],
            ],
        });
        setBanners(newData);

        // 更新排序到服务器
        try {
            const sort_orderData = newData.map((item, index) => ({
                id: item.id,
                sort_order: index + 1,
            }));
            await updateBannerSort(sort_orderData);
        } catch (error) {
            console.error('更新排序出错:', error);
            message.error('更新排序失败');
            // 恢复原始数据
            fetchBannerList();
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '排序',
            dataIndex: 'sort_order',
            key: 'sort_order',
            width: 80,
            render: () => <DragOutlined style={{ cursor: 'move', color: '#999' }} />,
        },
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '图片',
            dataIndex: 'image_url',
            key: 'image_url',
            render: (text) => text ? <img src={text} alt="轮播图" style={{ width: 120, height: 60, objectFit: 'cover' }} /> : '-',
        },
        {
            title: '链接类型',
            dataIndex: 'link_type',
            key: 'link_type',
            render: (text) => {
                const typeMap = {
                    'page': '小程序页面',
                    'webview': 'H5页面',
                    'none': '无链接',
                };
                return typeMap[text] || text;
            },
        },
        {
            title: '链接地址',
            dataIndex: 'link_url',
            key: 'link_url',
            ellipsis: true,
            render: (text) => text || '-',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <span style={{ color: status === 1 ? '#52c41a' : '#ff4d4f' }}>
                    {status === 1 ? '显示' : '隐藏'}
                </span>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            width: 180,
            render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        icon={<EditOutlined />}
                        size="small"
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除此轮播图吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="primary"
                            danger
                            icon={<DeleteOutlined />}
                            size="small"
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    // 处理添加轮播图
    const handleAdd = () => {
        setModalTitle('添加轮播图');
        setEditingId(null);
        form.resetFields();
        form.setFieldsValue({
            status: 1,
            link_type: 'page',
            sort_order: banners.length + 1,
        });
        setModalVisible(true);
    };

    // 处理编辑轮播图
    const handleEdit = (record) => {
        setModalTitle('编辑轮播图');
        setEditingId(record.id);
        form.setFieldsValue({
            title: record.title,
            image_url: record.image_url,
            link_type: record.link_type,
            link_url: record.link_url,
            status: record.status,
            sort_order: record.sort_order,
        });
        setModalVisible(true);
    };

    // 处理删除轮播图
    const handleDelete = async (id) => {
        try {
            const res = await deleteBanner(id);
            if (res.success) {
                message.success('删除成功');
                fetchBannerList();
            } else {
                message.error(res.message || '删除失败');
            }
        } catch (error) {
            console.error('删除轮播图出错:', error);
            message.error('删除失败');
        }
    };

    // 处理表单提交
    const handleSubmit = async (values) => {
        try {
            const data = { ...values };
            let res;

            if (editingId) {
                data.id = editingId;
                res = await updateBanner(data);
            } else {
                res = await createBanner(data);
            }

            if (res.success) {
                message.success(`${editingId ? '更新' : '添加'}成功`);
                setModalVisible(false);
                fetchBannerList();
            } else {
                message.error(res.message || `${editingId ? '更新' : '添加'}失败`);
            }
        } catch (error) {
            console.error(`${editingId ? '更新' : '添加'}轮播图出错:`, error);
            message.error(`${editingId ? '更新' : '添加'}失败`);
        }
    };
    const token = localStorage.getItem('token');
    // 上传配置
    const uploadProps = {
        name: 'file',
        action: '/api/v1/upload',
        headers: {
            Authorization: `Bearer ${token}`,
        },
        onChange(info) {
            if (info.file.status === 'done') {
                message.success(`${info.file.name} 上传成功`);
                form.setFieldsValue({
                    image_url: info.file.response.data,
                });
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败`);
            }
        },
    };

    return (
        <PageContainer>
            <Card>
                <div style={{ marginBottom: 16 }}>
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleAdd}
                    >
                        添加轮播图
                    </Button>
                </div>

                <DndProvider backend={HTML5Backend}>
                    <Table
                        columns={columns}
                        dataSource={banners}
                        rowKey="id"
                        loading={loading}
                        pagination={pagination}
                        onChange={(pagination) => setPagination(pagination)}
                        components={{
                            body: {
                                row: DraggableBodyRow,
                            },
                        }}
                        onRow={(record, index) => ({
                            index,
                            moveRow,
                        })}
                    />
                </DndProvider>

                <Modal
                    title={modalTitle}
                    visible={modalVisible}
                    onCancel={() => setModalVisible(false)}
                    footer={null}
                    width={600}
                >
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={handleSubmit}
                    >
                        <Form.Item
                            name="title"
                            label="标题"
                            rules={[{ required: true, message: '请输入标题' }]}
                        >
                            <Input placeholder="请输入标题" />
                        </Form.Item>

                        <Form.Item
                            name="image_url"
                            label="轮播图"
                            rules={[{ required: true, message: '请上传轮播图' }]}
                        >
                            <Input
                                placeholder="请上传轮播图"
                                addonAfter={
                                    <Upload {...uploadProps}>
                                        <Button icon={<UploadOutlined />}>上传</Button>
                                    </Upload>
                                }
                            />
                        </Form.Item>

                        <Form.Item
                            name="link_type"
                            label="链接类型"
                            rules={[{ required: true, message: '请选择链接类型' }]}
                        >
                            <Select placeholder="请选择链接类型">
                                <Select.Option value="page">小程序页面</Select.Option>
                                <Select.Option value="webview">H5页面</Select.Option>
                                <Select.Option value="none">无链接</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name="link_url"
                            label="链接地址"
                            rules={[{
                                required: false,
                                message: '请输入链接地址'
                            }]}
                        >
                            <Input placeholder="请输入链接地址" />
                        </Form.Item>

                        <Form.Item
                            name="status"
                            label="状态"
                            rules={[{ required: true, message: '请选择状态' }]}
                            initialValue={1}
                            valuePropName="checked"
                        >
                            <Switch checkedChildren="显示" unCheckedChildren="隐藏" defaultChecked />
                        </Form.Item>
                        <Form.Item
                            name="sort_order"
                            label="排序"
                            rules={[{ required: true, message: '请输入排序' }]}
                        >
                            <InputNumber min={0} placeholder="数值越小越靠前" style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item>
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                                <Button onClick={() => setModalVisible(false)}>取消</Button>
                                {editingId && (
                                    <Popconfirm
                                        title="确定要删除此轮播图吗？"
                                        onConfirm={() => {
                                            handleDelete(editingId);
                                            setModalVisible(false);
                                        }}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <Button danger>删除</Button>
                                    </Popconfirm>
                                )}
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </Card>
        </PageContainer>
    );
};
export default BannerManagement;